class AnimationState {
    constructor(public name: string, public ani: Laya.Animation) {}
    async play(startFrame: number, loop: boolean = false) {
        const target = this.ani;
        target.visible = true;
        return new Promise<Laya.Animation>((resolve) => {
            target.play(startFrame, loop);
            target.on(Laya.Event.COMPLETE, target, () => {
                resolve(target);
            });
        });
    }
}
export class AnimationManager<State extends string> {
    states = new Map<string, AnimationState>();
    /**
     * 辅助 Laya.Sprite 进行动画播放的库
     * @param target 目标对象
     * @param states 状态数组（可以进行分层设置，每个Manager都是一层，都是独立的）
     */
    constructor(public target: Laya.Sprite, states: State[]) {
        states.forEach((state) => {
            const ani = target.getChildByName(state)! as Laya.Animation;
            const animation = new AnimationState(state, ani);
            this.states.set(state, animation);
        });
    }
    status: State | "idle" = "idle";
    lastAni?: Laya.Animation;
    loopingCount = 0;
    /** 循环动画，这个动画会覆盖上次的动画 */
    loop(stateName: State, loopTimes: number = Infinity, startFrame = 0): void {
        const target = this.states.get(stateName);
        if (!target) return;
        this.stopRunningAnime();
        this.loopingCount = loopTimes;
        target.play(startFrame, true);
        this.lastAni = target.ani;
    }
    /**强制暂停正在播放中的动画 */
    stopRunningAnime() {
        if (this.loopingCount > 0) {
            this.loopingCount = 0;
        }
        if (this.lastAni) this.lastAni.visible = false;
        this.lastAni?.stop();
    }
    /** 使用父节点下面的 Animation 的 name属性 作为 stateName */
    async play(stateName: State, startFrame: number = 0) {
        const target = this.states.get(stateName);
        if (!target) return false;

        this.stopRunningAnime();

        return target.play(startFrame).then((lastAni) => {
            this.lastAni = lastAni;
            this.status = "idle";
            return this;
        });
    }
}
